package com.asseco.mio.codex.controllers;

import com.asseco.mio.BasicInfo;
import com.asseco.mio.DisciplineProcedure;
import com.asseco.mio.WorkPosition;
import com.asseco.mio.codex.DeleteReason;
import com.asseco.mio.codex.DisciplineProcedureForm;
import com.asseco.mio.codex.MeasuresTaken;
import com.asseco.mio.codex.ResponsibilityReason;
import com.asseco.mio.codex.ResponsibilityType;
import com.asseco.mio.core.model.AuditLog;
import com.asseco.mio.core.webapp.controller.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.Validator;

@Controller
@RequestMapping("/disciplineprocedureform*")
public class DisciplineProcedureFormController extends BaseFormController {

    private String bi1 = "";
    private GenericManager<DisciplineProcedure, String> disciplineProcedureManager = null;
    private GenericManager<WorkPosition, String> workPositionManager = null;
    private GenericManager<BasicInfo, String> basicInfoManager = null;
    private GenericManager<ResponsibilityType, String> responsibilityTypeManager = null;
    private GenericManager<ResponsibilityReason, String> responsibilityReasonManager = null;
    private GenericManager<MeasuresTaken, String> measuresTakenManager = null;
    private GenericManager<AuditLog, String> auditLoggerManager = null;
     private GenericManager<DeleteReason, String> deleteReasonManager = null;

    public String getBi1() {
        return bi1;
    }

    public void setBi1(String bi1) {
        this.bi1 = bi1;
    }
    @Autowired(required = false)
    Validator validator;

    @Autowired
    public void setWorkPositionManager(@Qualifier("workPositionManager") GenericManager<WorkPosition, String> workPositionManager) {
        this.workPositionManager = workPositionManager;
    }

    @Autowired
    public void setBasicInfoManager(@Qualifier("basicInfoManager") GenericManager<BasicInfo, String> basicInfoManager) {
        this.basicInfoManager = basicInfoManager;
    }

    @Autowired
    public void setDisciplineProcedureManager(@Qualifier("disciplineProcedureManager") GenericManager<DisciplineProcedure, String> disciplineProcedureManager) {
        this.disciplineProcedureManager = disciplineProcedureManager;
    }

    @Autowired
    public void setResponsibilityTypeManagerManager(@Qualifier("responsibilityTypeManager") GenericManager<ResponsibilityType, String> responsibilityTypeManager) {
        this.responsibilityTypeManager = responsibilityTypeManager;
    }

    @Autowired
    public void setResponsibilityReasonManagerManager(@Qualifier("responsibilityReasonManager") GenericManager<ResponsibilityReason, String> responsibilityReasonManager) {
        this.responsibilityReasonManager = responsibilityReasonManager;
    }

    @Autowired
    public void setMeasuresTakenManagerManager(@Qualifier("measuresTakenManager") GenericManager<MeasuresTaken, String> measuresTakenManager) {
        this.measuresTakenManager = measuresTakenManager;
    }

    @Autowired
    public void setAuditLoggerManager(GenericManager<AuditLog, String> auditLoggerManager) {
        this.auditLoggerManager = auditLoggerManager;
    }

     @Autowired
    public void setDeleteReasonManager(GenericManager<DeleteReason, String> deleteReasonManager) {
        this.deleteReasonManager = deleteReasonManager;
    }

    public DisciplineProcedureFormController() {
        setCancelView("redirect:searchDisciplineProcedures");
        setSuccessView("redirect:searchDisciplineProcedures");
    }

    @ModelAttribute
    public DisciplineProcedureForm disciplineProcedureForm(String bi) {
        if (bi == null) {
            if (bi1.equals("")) {
                DisciplineProcedureForm x = new DisciplineProcedureForm(new DisciplineProcedure(), this.basicInfoManager.getAll(), getAllActiveRespType(this.responsibilityTypeManager.getAll()), getAllActiveRespReason(this.responsibilityReasonManager.getAll()), getAllActiveMeasureTaken(this.measuresTakenManager.getAll()));
                return x;
            } else {
                DisciplineProcedure dp = new DisciplineProcedure();
                dp.setWorkPosition(workPositionManager.get(bi1));
                DisciplineProcedureForm x = new DisciplineProcedureForm(dp, this.basicInfoManager.getAll(), getAllActiveRespType(this.responsibilityTypeManager.getAll()), getAllActiveRespReason(this.responsibilityReasonManager.getAll()), getAllActiveMeasureTaken(this.measuresTakenManager.getAll()));
                return x;
            }
        }
        this.setBi1(bi);
        DisciplineProcedure dp = new DisciplineProcedure();
        dp.setWorkPosition(workPositionManager.get(bi1));
        DisciplineProcedureForm x = new DisciplineProcedureForm(dp, this.basicInfoManager.getAll(), getAllActiveRespType(this.responsibilityTypeManager.getAll()), getAllActiveRespReason(this.responsibilityReasonManager.getAll()), getAllActiveMeasureTaken(this.measuresTakenManager.getAll()));
        return x;
    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected DisciplineProcedureForm showForm(HttpServletRequest request)
            throws Exception {

        String id = request.getParameter("id");
        String bi = request.getParameter("bi");
        DisciplineProcedureForm x = new DisciplineProcedureForm(null, this.basicInfoManager.getAll(), getAllActiveRespType(this.responsibilityTypeManager.getAll()), getAllActiveRespReason(this.responsibilityReasonManager.getAll()), getAllActiveMeasureTaken(this.measuresTakenManager.getAll()), this.deleteReasonManager.getAll());
        if (!StringUtils.isBlank(id)) {
            x.setDisciplineProcedure(disciplineProcedureManager.get(id));
            this.setBi1(x.getDisciplineProcedure().getWorkPosition().getId());

            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "discpiplineProcedureform", "discipline.show", x.getDisciplineProcedure().getWorkPosition().getEmployment().getLastName(),
                    "", request.getRemoteHost(), new Date()));
        }
        if (!StringUtils.isBlank(bi)) {
            x = this.disciplineProcedureForm(bi);
        }

        return x;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(DisciplineProcedureForm disciplineProcedureForm, BindingResult errors, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        if (request.getParameter("cancel") != null) {
            this.setBi1("");
            disciplineProcedureForm.setDisciplineProcedure(null);
            return getCancelView();
        }
        if (validator != null) { // validator is null during testing
            //validator.validate(disciplineProcedureForm, errors);

            if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
             
                 return "disciplineprocedureform";
                
            }
        }

        log.debug("entering 'onSubmit' method...");

        boolean isNew = (disciplineProcedureForm.getDisciplineProcedure().getId().equals(""));
        String success = getSuccessView();
        Locale locale = request.getLocale();

        if (!disciplineProcedureForm.getSavedReason().getId().equals("")) {

            disciplineProcedureManager.remove(disciplineProcedureForm.getDisciplineProcedure().getId());

            DeleteReason delRes = deleteReasonManager.get(disciplineProcedureForm.getSavedReason().getId());
                   
            String info1 = disciplineProcedureForm.getDisciplineProcedure().toString();
            String info2 = delRes.toString();

            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "discpiplineProcedureform", "discipline.delete", info1, info2, request.getRemoteHost(), new Date()));
            
            saveMessage(request, getText("disciplineProcedure.deleted", locale));
            disciplineProcedureForm.setDisciplineProcedure(null);
            success = "searchDisciplineProcedures";
        } else {
            DisciplineProcedure x = disciplineProcedureForm.getDisciplineProcedure();
            WorkPosition y = workPositionManager.get(bi1);
            x.setWorkPosition(y);
            disciplineProcedureManager.save(x);
            String key = (isNew) ? "disciplineProcedure.added" : "disciplineProcedure.updated";
            saveMessage(request, getText(key, locale));
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "discpiplineProcedureform", key, disciplineProcedureForm.getDisciplineProcedure().getId(),
                    disciplineProcedureForm.getDisciplineProcedure().getId(), request.getRemoteHost(), new Date()));
                    success="searchDisciplineProcedures";
                    disciplineProcedureForm.setDisciplineProcedure(null);
        }

        return success;

    }

    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        super.initBinder(request, binder);
        SimpleDateFormat dateFormat =
                new SimpleDateFormat(getText("dd/MM/yyyy", request.getLocale()));
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
    }

    public List getAllActiveRespType(List<ResponsibilityType> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            ResponsibilityType ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActiveBasicInfo(List<BasicInfo> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            BasicInfo ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActiveRespReason(List<ResponsibilityReason> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            ResponsibilityReason ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActiveMeasureTaken(List<MeasuresTaken> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            MeasuresTaken ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }
}
